using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using Excel;
using System.IO;
namespace IceAge
{
    public partial class GridForm : DockContent
    {
        public GridForm()
        {
            InitializeComponent();
        }
        public object[] parameters;
        private bool SuspendStatus = false;
       
        private void GridForm_Load(object sender, EventArgs e)
        {
            try
            {                
                BuidGridView(this.Tag.ToString());
                if (parameters[1].ToString() == "Y")
                    gridControl1.ReadOnly = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); 
            }
        }

        private void BuidGridView(string table_name)
        {
            DataSet data = new DataSet();
            DataTable table = new DataTable("GridView");
            foreach (DataRow row in CommonLibrary.XML_DATA.Tables["GridSchema"].Rows)
            {
                if (row["TableName"].ToString() == table_name)
                {
                    DataColumn col = new DataColumn(row["FieldName"].ToString());
                    Xceed.Grid.DataBoundColumn colx = new Xceed.Grid.DataBoundColumn(row["FieldName"].ToString());
                    switch (row["DataType"].ToString())
                    {
                        case "C":
                            col.DataType = System.Type.GetType("System.Decimal");
                            colx.FormatSpecifier = global::IceAge.Properties.Settings.Default.CurrencyFormat;
                            break;
                        case "N":
                            col.DataType = System.Type.GetType("System.Double");
                            colx.FormatSpecifier = global::IceAge.Properties.Settings.Default.NumberFormat;
                            break;
                        case "D":
                            col.DataType = System.Type.GetType("System.DateTime");
                            colx.FormatSpecifier = global::IceAge.Properties.Settings.Default.DateDisplayFormat;
                            break;
                        case "S":
                            col.DataType = System.Type.GetType("System.String");
                            break;
                        default:
                            col.DataType = System.Type.GetType("System.String");
                            break;
                    }
                    colx.Title = row["VnCaption"].ToString();
                    colx.Width = Convert.ToInt32(row["Width"]);
                    switch (row["Align"].ToString())
                    {
                        case "C":
                            colx.HorizontalAlignment = Xceed.Grid.HorizontalAlignment.Center;
                            break;
                        case "L":
                            colx.HorizontalAlignment = Xceed.Grid.HorizontalAlignment.Left;
                            break;
                        case "R":
                            colx.HorizontalAlignment = Xceed.Grid.HorizontalAlignment.Right;
                            break;
                        default:
                            colx.HorizontalAlignment = Xceed.Grid.HorizontalAlignment.Default;
                            break;
                    }

                    if (row["DropDown"] != null)
                    {
                        if (Convert.ToInt16(row["DropDown"]) > 0)
                        {
                            DataSet combo_data = CommonLibrary.ExecuteReader("0115", new object[1] { row["DropDown"] });
                            Xceed.Grid.Editors.ComboBoxEditor editor = new Xceed.Grid.Editors.ComboBoxEditor();
                            Xceed.Grid.Viewers.ComboBoxViewer viewer = new Xceed.Grid.Viewers.ComboBoxViewer();   
                            editor.TemplateControl.AllowFreeText = false;
                            editor.TemplateControl.BorderStyle = Xceed.Editors.EnhancedBorderStyle.None;

                            DataSet editor_data = combo_data.Copy();
                            DataSet viewer_data = combo_data.Copy();
                            
                            editor.SetDataBinding(editor_data, editor_data.Tables[0].TableName);
                            editor.ValueMember = editor_data.Tables[0].Columns[0].ColumnName;
                            editor.DisplayFormat = "%" + editor_data.Tables[0].Columns[1].ColumnName + "%";
                            editor.Columns[0].Visible = false;
                            editor.Columns[1].Width = Convert.ToInt32(row["Width"]);
                            colx.CellEditorManager = editor;

                            viewer.SetDataBinding(viewer_data, viewer_data.Tables[0].TableName);
                            viewer.ValueMember = viewer_data.Tables[0].Columns[0].ColumnName;
                            viewer.DisplayFormat = "%" + viewer_data.Tables[0].Columns[1].ColumnName + "%";
                            colx.CellViewerManager = viewer;
                        }
                    }
                    colx.VisibleIndex = Convert.ToInt16(row["Sequence"]);
                    colx.Tag = new object[2] { row["Index"], row["InputValue"] };
                    table.Columns.Add(col);
                    gridControl1.Columns.Add(colx);
                }
            }
            data.Tables.Add(table);
            gridControl1.SetDataBinding(data, "GridView");

            foreach (DataRow row in CommonLibrary.XML_DATA.Tables["GridSchema"].Rows)
            {
                if (row["TableName"].ToString() == table_name)
                {
                    Xceed.Grid.SummaryCell cellx = (Xceed.Grid.SummaryCell)summaryRow1.Cells[row["FieldName"].ToString()];
                    cellx.StatFieldName = row["FieldName"].ToString();
                    switch (row["Function"].ToString())
                    {
                        case "SUM":
                            cellx.StatFunction = Xceed.Grid.StatFunction.Sum;
                            break;
                        case "COUNT":
                            cellx.StatFunction = Xceed.Grid.StatFunction.Count;
                            break;
                        default:
                            break;
                    }

                    Xceed.Grid.ValueCell cellv = (Xceed.Grid.ValueCell)valueRow1.Cells[row["FieldName"].ToString()];
                    if (Convert.ToInt16(row["Index"]) > 0)
                    {
                        cellv.ReadOnly = false;
                        cellv.BackColor = Color.Yellow;
                    }
                    else
                    {
                        cellv.ReadOnly = true;
                    }
                }
            }
        }

        private void Load_Grid()
        {
            object[] param = new object[gridControl1.Columns.Count];
            foreach (Xceed.Grid.Column col in gridControl1.Columns)
            {
                if (col.Tag != null)
                {
                    if (Convert.ToInt16(((object[])col.Tag)[0]) > 0)
                    {
                        if (valueRow1.Cells[col.FieldName].Value != null)
                            param[Convert.ToInt16(((object[])col.Tag)[0]) - 1] = valueRow1.Cells[col.FieldName].Value;
                        else
                        {
                            if (col.DataType.ToString() == "System.DateTime")
                                param[Convert.ToInt16(((object[])col.Tag)[0]) - 1] = CommonLibrary.TRAN_DATE;
                            else if (col.DataType.ToString() == "System.Decimal"
                                || col.DataType.ToString() == "System.Double"
                                || col.DataType.ToString() == "System.Byte"
                                || col.DataType.ToString() == "System.Int32")
                                param[Convert.ToInt16(((object[])col.Tag)[0]) - 1] = 0;
                            else
                                param[Convert.ToInt16(((object[])col.Tag)[0]) - 1] = string.Empty;
                        }
                    }
                }
            }
            DataSet dataSet1 = CommonLibrary.ExecuteReader(this.Tag.ToString(), param);
            if (!SuspendStatus)
                SuspendStatus = true;
            if (gridControl1.SortedColumns.Count > 0)
                gridControl1.SortedColumns.Clear(); 
            gridControl1.SetDataBinding(dataSet1, dataSet1.Tables[0].TableName);                        
            bindingSource1.DataSource = gridControl1.DataSource;
            bindingSource1.DataMember = gridControl1.DataMember;
            SuspendStatus = false; 
            
        }
        private void Commit_Changes()
        {
            if (((DataSet)gridControl1.DataSource).Tables[0].GetChanges() != null)
            {
                object[] param = new object[gridControl1.Columns.Count + 2];
                foreach (DataRow row in ((DataSet)gridControl1.DataSource).Tables[0].GetChanges().Rows)
                {
                    foreach (Xceed.Grid.Column col in gridControl1.Columns)
                    {
                        if (col.Tag != null)
                        {
                            if (Convert.ToInt16(((object[])col.Tag)[1]) > 0)
                            {
                                if (row[col.FieldName] != DBNull.Value)
                                    param[Convert.ToInt16(((object[])col.Tag)[1]) - 1] = row[col.FieldName];
                                else
                                {
                                    if (col.DataType.ToString() == "System.DateTime")
                                        param[Convert.ToInt16(((object[])col.Tag)[1]) - 1] = CommonLibrary.TRAN_DATE;
                                    else if (col.DataType.ToString() == "System.Decimal"
                                        || col.DataType.ToString() == "System.Double")
                                        param[Convert.ToInt16(((object[])col.Tag)[1]) - 1] = 0;
                                    else
                                        param[Convert.ToInt16(((object[])col.Tag)[1]) - 1] = string.Empty;
                                }
                            }
                        }
                    }
                    param[gridControl1.Columns.Count] = CommonLibrary.USER_NAME;
                    param[gridControl1.Columns.Count + 1] = CommonLibrary.TRAN_DATE;
                    CommonLibrary.ExecuteNonquery(this.Tag.ToString(), param);
                }
                ((DataSet)gridControl1.DataSource).Tables[0].AcceptChanges();
            }            
        }
        private void Data_Load()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "Excel Files (*.xls)|*.xls";
            openFileDialog.AddExtension = true;
            if (openFileDialog.ShowDialog(this) != DialogResult.OK)
                return;
            FileStream stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read);
            IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
            excelReader.IsFirstRowAsColumnNames = true;
            DataSet _book = excelReader.AsDataSet();
            excelReader.Close();

            DataSet obj = ((DataSet)gridControl1.DataSource).Copy();
            obj.Clear();
            foreach (DataRow _cell in _book.Tables[0].Rows)
            {
                bool InvalidRow = false;
                DataRow _row = obj.Tables[0].NewRow();
                foreach (Xceed.Grid.Column col in gridControl1.Columns)
                {
                    if (col.Tag != null)
                    {
                        if (Convert.ToInt16(((object[])col.Tag)[1]) > 0)
                        {
                            if (_cell[col.FieldName] == null)
                                InvalidRow = true;
                            else
                                _row[col.FieldName] = _cell[col.FieldName];
                        }
                    }
                }
                if (InvalidRow)
                    continue;
                obj.Tables[0].Rows.Add(_row);

            }
            gridControl1.SetDataBinding(obj, obj.Tables[0].TableName);
            MessageBox.Show("Import du lieu vao he thong tu file " + openFileDialog.FileName + " thanh cong!",
                this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void GridForm_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.F9)
                {
                    Load_Grid();
                }
                else if (e.KeyCode == Keys.F11)
                {
                    Commit_Changes();                    
                }
                else if (e.KeyCode == Keys.F12)
                {
                    Data_Load();
                }
                else if (e.KeyCode == Keys.F8)
                {
                    AddNew();
                }
                else if (e.KeyCode == Keys.F10)
                {
                    //CommonLibrary.ExportToExcel(gridControl1);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }  
        }

        private void gridControl1_CurrentRowChanged(object sender, EventArgs e)
        {
            if (gridControl1.DataSource == null)
                return;
            if (valueRow1.IsCurrent)
                return;
            if (insertionRow1.IsCurrent)
                return;
            if (gridControl1.CurrentRow == null)
                return;
            bindingSource1.Position = ((Xceed.Grid.DataRow)gridControl1.CurrentCell.ParentRow).Index;            
            //for (int i = 0; i < gridControl1.DataRows.Count; i++)
            //{
            //    if (gridControl1.DataRows[i].IsCurrent)
            //    {
            //        bindingSource1.Position = i;
            //        return;
            //    }
            //}
        }

        private void bindingSource1_PositionChanged(object sender, EventArgs e)
        {
            try
            {
                
                //if (bindingSource1.Position >= gridControl1.DataRows.Count)
                //{
                //    insertionRow1.BringIntoView();
                //    return;
                //}

                if (bindingSource1.Position >= gridControl1.DataRows.Count
                    || bindingSource1.Position < 0)
                    return;
                if (gridControl1.SortedColumns.Count > 0)
                    return;
                if (SuspendStatus)
                    return;
                gridControl1.SelectedRows.Clear();
                gridControl1.DataRows[bindingSource1.Position].IsSelected = true;
                gridControl1.DataRows[bindingSource1.Position].BringIntoView();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void gridControl1_Sorted(object sender, EventArgs e)
        {
            if (!SuspendStatus)
                SuspendStatus = true;
        }

        private void gridControl1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (parameters[0].ToString() == string.Empty)
                return;
            if (gridControl1.DataRows.Count <= 0)
                return;

            object[] param = new object[gridControl1.Columns.Count];
            foreach (Xceed.Grid.Column col in gridControl1.Columns)
            {
                if (col.Tag != null)
                {
                    if (Convert.ToInt16(((object[])col.Tag)[1]) > 0)
                    {
                        param[Convert.ToInt16(((object[])col.Tag)[1]) - 1] =
                                gridControl1.CurrentCell.ParentRow.Cells[col.FieldName].Value;
                    }
                }
            }
            Form obj = (Form)Activator.CreateInstance(
                        Type.GetType(parameters[0].ToString(), true, true));
            obj.Text = this.Text;
            obj.Tag = param;
            obj.ShowDialog(this.DockPanel.Parent);
        }
        private void AddNew()
        {
            if (parameters[0].ToString() == string.Empty)
                return;
            //if (gridControl1.DataRows.Count <= 0)
            //    return;

            object[] param = new object[gridControl1.Columns.Count];
            //foreach (Xceed.Grid.Column col in gridControl1.Columns)
            //{
            //    if (col.Tag != null)
            //    {
            //        if (Convert.ToInt16(((object[])col.Tag)[1]) > 0)
            //        {
            //            param[Convert.ToInt16(((object[])col.Tag)[1]) - 1] =
            //                    gridControl1.CurrentCell.ParentRow.Cells[col.FieldName].Value;
            //        }
            //    }
            //}
            Form obj = (Form)Activator.CreateInstance(
                        Type.GetType(parameters[0].ToString(), true, true));
            obj.Text = this.Text;
            obj.Tag = param;
            obj.ShowDialog(this.DockPanel.Parent);
        }
    }
}